package com.ruoyi.web.controller.order;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.domain.TOrderDetail;
import org.apache.poi.ss.usermodel.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.TOrder;
import com.ruoyi.system.service.ITOrderService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 订单管理Controller
 * 
 * @author ruoyi
 * @date 2020-10-16
 */
@Controller
@RequestMapping("/order/order")
public class TOrderController extends BaseController
{
    private String prefix = "order/order";

    @Autowired
    private ITOrderService tOrderService;

    @RequiresPermissions("order:order:view")
    @GetMapping()
    public String order()
    {
        return prefix + "/order";
    }

    @GetMapping("/orderInfo")
    public String orderInfo(@RequestParam String ids, ModelMap mmap)
    {
        Long[] idArr = Convert.toLongArray(ids);
        List<TOrder> tOrders = tOrderService.selectTOrderByIds(Arrays.asList(idArr));
        mmap.put("tOrders", tOrders);
        return prefix + "/orderInfo";
    }

    /**
     * 查询订单管理列表
     */
    @RequiresPermissions("order:order:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TOrder tOrder)
    {
        startPage();
        List<TOrder> list = tOrderService.selectTOrderList(tOrder);
        Double totalSum = tOrderService.selectTOrderListTotalSum(tOrder);
        TableDataInfo dt = getDataTable(list);
        dt.setMsg(totalSum+"");
        return dt;
    }


    /**
     * 查询订单管理列表
     */
    @RequiresPermissions("order:order:list")
    @PostMapping("/totalSum")
    @ResponseBody
    public Double totalSum(TOrder tOrder)
    {
        startPage();
        Double totalSum = tOrderService.selectTOrderListTotalSum(tOrder);
        return totalSum;
    }

    /**
     * 导出订单管理列表
     */
    @RequiresPermissions("order:order:export")
    @Log(title = "订单管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TOrder tOrder)
    {
        List<TOrder> list = tOrderService.selectTOrderList(tOrder);
        ExcelUtil<TOrder> util = new ExcelUtil<TOrder>(TOrder.class);
        return util.exportExcel(list, "order");
    }

    /**
     * 新增订单管理
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存订单管理
     */
    @RequiresPermissions("order:order:add")
    @Log(title = "订单管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(TOrder tOrder)
    {
        return toAjax(tOrderService.insertTOrder(tOrder));
    }

    /**
     * 修改订单管理
     */
    @GetMapping("/edit/{orderId}")
    public String edit(@PathVariable("orderId") Long orderId, ModelMap mmap)
    {
        TOrder tOrder = tOrderService.selectTOrderById(orderId);
        mmap.put("tOrder", tOrder);
        return prefix + "/edit";
    }

    /**
     * 修改保存订单管理
     */
    @RequiresPermissions("order:order:edit")
    @Log(title = "订单管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(TOrder tOrder)
    {
        return toAjax(tOrderService.updateTOrder(tOrder));
    }

    /**
     * 删除订单管理
     */
    @RequiresPermissions("order:order:remove")
    @Log(title = "订单管理", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(tOrderService.deleteTOrderByIds(ids));
    }



    @Log(title = "订单管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions("order:order:import")
    @PostMapping("/import")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
//        ExcelUtil<TOrder> util = new ExcelUtil<TOrder>(TOrder.class);
//        List<TOrder> orderList = util.importExcel(file.getInputStream());

        Workbook wb = WorkbookFactory.create(file.getInputStream());
        List<TOrder> orderList = new ArrayList<TOrder>();
        Sheet sheet = wb.getSheetAt(0);
        if (sheet == null)
        {
            return AjaxResult.success("文件sheet不存在");
        }
        //获取表头
        Row heard = sheet.getRow(0);

        Map<Integer,String> teachers = new HashMap<>();

        int receiver=0;
        for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++)
        {
            Cell cell = heard.getCell(i);
            if (StringUtils.isNotNull(cell))
            {
                String value = cell.getStringCellValue();
                if ("收件人".equals(value)){
                    receiver=i;
                    break;
                }

                if(value.contains("老师")){
                    String teacher = value.substring(0,value.indexOf("老师"));
                    teachers.put(i,teacher);
                }
            }
        }
        if (receiver == 0) {
            return AjaxResult.success("没有画家的字画信息");
        }
        int rows = sheet.getPhysicalNumberOfRows();
        for (int i = 1; i < rows ; i++) {
            Row row = sheet.getRow(i);
            TOrder tOrder = new TOrder();
            tOrder.setReceiver(getCellStringValue(row,receiver));
            tOrder.setOrderNo(this.generateOrderNo());

            tOrder.setConstact(getCellStringValue(row,receiver));

            tOrder.setOrderTime(new Date());

            tOrder.setMobile(getCellStringValue(row,receiver+1));
            tOrder.setAddress(getCellStringValue(row,receiver+3));
            tOrder.setComment(getCellStringValue(row,receiver+4));

            String payWay = getCellStringValue(row,receiver+5);

            tOrder.setPayWay(OrderConstant.PAY_WAY_AFTER);
            if (payWay!=null){
            if(payWay.contains("微信"))
            {
                tOrder.setPayWay(OrderConstant.PAY_WAY_WEIXIN);

            }else if(payWay.contains("支付宝")){
                tOrder.setPayWay(OrderConstant.PAY_WAY_ALIPAY);

            }else if (payWay.contains("银行")){
                tOrder.setPayWay(OrderConstant.PAY_WAY_BANK);
            }
            }
            tOrder.setLogistics(OrderConstant.LOGISTICS_SHUNFENG);
            List<TOrderDetail> orderDetailList = new ArrayList<>();

            StringBuilder sb = new StringBuilder();



            for (int j = 1 ; j < receiver ; j++) {

                String content =getCellStringValue(row,j);
                if (StringUtils.isNotBlank(content)){

                    String[] details=  content.split("，");
                    for (int k = 0; k < details.length ; k++) {
                        TOrderDetail tOrderDetail = new TOrderDetail();
                        String detail = details[k];
                        String pattern = "([1-9]\\d*|[1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*)元";
                        Pattern r = Pattern.compile(pattern);
                        Matcher m = r.matcher(detail);

                        if (m.find()){
                           String price =  m.group().replace("元","");
                           tOrderDetail.setAmount(Double.parseDouble(price));
                           tOrderDetail.setPrice(Double.parseDouble(price));
                        }
                        pattern = "[1-9]\\d*X[1-9]\\dcm|[1-9]\\d×X[1-9]\\dCM" ;
                        Pattern rs = Pattern.compile(pattern);
                        Matcher ms = rs.matcher(detail);
                        if (ms.find()){
                            tOrderDetail.setSpec(ms.group());
                        }
                        tOrderDetail.setGoodsName(teachers.get(j)+"："+detail.substring(0,detail.indexOf("规格")));
                        tOrderDetail.setQuantity(1L);
                        tOrderDetail.setUnit("幅");
                        orderDetailList.add(tOrderDetail);
                        sb.append(tOrderDetail.getGoodsName()+"，");
                    }
                }
            }
            if (tOrder.getTOrderDetailList() == null) {
                tOrder.setTOrderDetailList(orderDetailList);
            }
            else
            {
                tOrder.getTOrderDetailList().addAll(orderDetailList);
            }
            Double sum = 0.0d;
            for (TOrderDetail td : orderDetailList) {
                sum += td.getAmount();
            }
            tOrder.setAmount(sum);
            tOrder.setSummary(sb.toString());
            orderList.add(tOrder);
        }

        String message = tOrderService.importOrder(orderList, updateSupport);
        return AjaxResult.success(message);
    }


    private String getCellStringValue(Row row,int i){
        Cell cell = row.getCell(i, Row.MissingCellPolicy.RETURN_NULL_AND_BLANK);
        if(cell==null)
            return null;
        cell.setCellType(CellType.STRING);
      return   row.getCell(i, Row.MissingCellPolicy.RETURN_NULL_AND_BLANK)==null?null:row.getCell(i, Row.MissingCellPolicy.RETURN_NULL_AND_BLANK).getStringCellValue();
    }

    private String generateOrderNo(){

        StringBuilder sb = new StringBuilder();
        sb.append("XS-");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        sb.append(simpleDateFormat.format(new Date())+"-");

        sb.append(getRandomString(6));
        return sb.toString();
    }

    public static String getRandomString(int stringLength) {
        String string = "0123456789";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < stringLength; i++) {
            int index = (int) Math.floor(Math.random() * string.length());//向下取整0-25
            sb.append(string.charAt(index));
        }
        return sb.toString();
    }

}
